//
//  TSZPictureView.swift
//  微博天下
//
import UIKit
 /// 使用UICollectionView进行布局
import SDWebImage
//全局的注册cell的ID
private let  PrictureIdentifier = "PrictureIdentifier"

//选中图片的通知
let TSZMricoblogPritureActionNotification =  "TSZMricoblogPritureActionNotification"

// 大图 路径 URL 的key
let TSZMricoblogCellSelectPictureURLKey = "TSZMricoblogCellSelectPictureURLKey"
/// IndexPath 的 KEY
let TSZMricoblogCellSelectPictureIndexKey = "TSZMricoblogCellSelectPictureIndexKey"

class TSZPictureView: UICollectionView {
    /**
    * 先在这里得到需要显示的数据
    */
    
    var mricoblogData: TSZHomeMircoblogModel?{
        didSet{
            sizeToFit()
            //刷新数据
            reloadData()
        }
    }
    
   override func sizeThatFits(size: CGSize) -> CGSize{
        return calculateCollView()
    }
    
    //计算试图的大小
    private func calculateCollView() ->CGSize{
        //1、准备每一个button的大小
        let itemSize = CGSize(width: 90, height: 90)
        
        pictureLayout.itemSize = itemSize
        //图片之间的间距
        let pictureMargin: CGFloat = 10
        //设置列数 
        let colNumber: Int = 3
        //根据模型中pic_urls 这个数组的count 去判断如何显示
       
        let count = mricoblogData?.pictureURLs?.count ?? 0
        
        if count == 0{
            return CGSizeZero
        }
        if count == 1 {
            //从SDWebImage 获取图片的大小
            
            //拿出的key就是URL的完整的字符串的路径
            let key = mricoblogData!.pictureURLs![0].absoluteString
            
            //提示的image 未必一定会被缓存下来
            let image = SDWebImageManager
            .sharedManager().imageCache.imageFromDiskCacheForKey(key)
            //如果图像不存在的默认就是默认的大小
            var size = CGSize(width: 150, height: 120)
            //判断图像是否存在
            if image != nil{
                size = image.size
            }
            //对图片的尺寸进行判断
            size.width = size.width < 40 ? 40 : size.width
            size.width = size.width  > UIScreen.mainScreen().bounds.width ? 150 : size.width
            
            pictureLayout.itemSize = size
            return size
            
        }
        
        if count == 4 {
            let width = itemSize.width * 2 + pictureMargin
            return CGSize(width: width, height: width)
        }
        //其他的情况 2 3 5  6 7 8 9 ,计算行数
        let row  = (count - 1) / colNumber + 1
        
        //计算宽度
        let width = itemSize.width * CGFloat(colNumber) + pictureMargin * (CGFloat(colNumber) - 1)
        
        //计算高度
        let height = itemSize.height * CGFloat(row) + pictureMargin * (CGFloat(row) - 1)
        
        return CGSize(width: width, height: height)
        
    }
    /**
    * 图片的布局
    */
    private let pictureLayout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    
    //重写init方法
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: pictureLayout)
        
        backgroundColor = UIColor.lightGrayColor()
        //注册 cell
        registerClass(statusPictureCell.self, forCellWithReuseIdentifier: "PrictureIdentifier")
        //实现数据源方法
        self.dataSource = self
        self.delegate = self
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

//MARK - collection的数据源方法 ,使用扩展去进行
extension TSZPictureView:UICollectionViewDataSource , UICollectionViewDelegate {
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return mricoblogData?.pictureURLs?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PrictureIdentifier, forIndexPath: indexPath) as! statusPictureCell
        cell.imageURL = mricoblogData!.pictureURLs![indexPath.item]
        
        return cell
    }
    
    //MARK: 选择点击的方法
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        /*
        // 要传递什么内容？
        // 1. URL的数组
        // 2. 用户选择的 indexPath
        name: 通知的名字，向通知中心发送，由通知中心向所有的监听者`广播`
        object: 发生事件的时候，传递一个对象，可以是 self
        userInfo: 字典，可以随着通知发送更多的消息
        */
        
        //写测试代码，知道 cell在屏幕中的位置
//        let v = UIView()
//        v.backgroundColor = UIColor.redColor()
//        v.frame = cellScreenFrame(indexPath)
//        UIApplication.sharedApplication().keyWindow?.addSubview(v)
        
        //点击图片就会发出通知
        NSNotificationCenter.defaultCenter().postNotificationName(TSZMricoblogPritureActionNotification, object: self, userInfo: [TSZMricoblogCellSelectPictureURLKey : mricoblogData!.largePictureURLs!,TSZMricoblogCellSelectPictureIndexKey: indexPath])
    }
    
    
    //MARK: cellScreenFrame 计算cell在屏幕上的坐标位置
    func cellScreenFrame(indexPath: NSIndexPath)  -> CGRect {
        let cell = self.cellForItemAtIndexPath(indexPath)!
        //知道 cell 在主窗口的位置，self 是 cell 的父视图, cell 的 frame 是相对父视图的坐标  ,主窗口就是父视图
        return convertRect(cell.frame, toCoordinateSpace: UIApplication.sharedApplication().keyWindow!)
    }
    
    
    //MARK: 计算在屏幕上放大全屏后的坐标
    func cellFullScreenFrame(indexPath: NSIndexPath)  ->CGRect{
        //利用缩略图的宽高比去计算目标位置
        let key = mricoblogData!.pictureURLs![indexPath.item].absoluteString
        
        let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
        
        //根据缩略图计算比例
        let scale = image.size.height / image.size.width
        
        let screenSize = UIScreen.mainScreen().bounds.size
        
        let height = screenSize.width * scale
        
        //考虑到长短图的问题
        var y: CGFloat = 0
        if height < screenSize.height {
            y = (screenSize.height - height) * 0.5
        }
        return CGRect(x: 0, y: y, width: screenSize.width, height: height)
    }
}




//自定义cell的位置在这里
private class statusPictureCell: UICollectionViewCell{
    
    var imageURL: NSURL? {
        didSet{
            iconView.sd_setImageWithURL(imageURL!)
            
        gifImageView.hidden = ((imageURL!.absoluteString as NSString).pathExtension.lowercaseString != "gif")
        }
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        //设置UI
        setupUI()
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        contentView.addSubview(iconView)
        
        iconView.addSubview(gifImageView)
        iconView.ff_Fill(contentView)
        
         gifImageView.ff_AlignInner(type: ff_AlignType.BottomRight, referView: iconView, size: nil)
    }
    /**
    * 懒加载 图
    */
    private lazy var iconView:UIImageView = {
            let iconView = UIImageView()
            iconView.contentMode = UIViewContentMode.ScaleAspectFill
            iconView.clipsToBounds = true
            return iconView
        }()
    //GIF图片
    private lazy var gifImageView:UIImageView = {
        let iv = UIImageView(image: UIImage(named: "timeline_image_gif"))
        return iv
        }()
}




